﻿using System;
using System.Collections.Generic;
using System.Linq;
using JohnHolliday.Caml.Net;
using Microsoft.SharePoint;
using WoltersKluwer.SPChainGang.Core.Data.Entity;
using WoltersKluwer.SPChainGang.Core.ExtensionMethods;
using WoltersKluwer.SPChainGang.Core.Util;

namespace WoltersKluwer.SPChainGang.Core.Data.Repository
{
    class ReportsRepository : RepositoryBase<ReportRecord>, IReportsRepository<SPListItem,ReportRecord>
    {
        public ReportsRepository(SPWeb web) : base(web, Constants.GlobalConstants.ReportsListName)
        {
        }

        public ReportsRepository(SPSite site)
            : base(site.RootWeb, Constants.GlobalConstants.ReportsListName)
        {
        }

        public SPListItem CreateNewReport(string reportName)
        {
            var list = listResolver.List;
            var folder = list.OptimizedAddItem(String.Empty, SPFileSystemObjectType.Folder, LinkHelpers.StripInvalidCharacters(reportName));
            folder[SPBuiltInFieldId.Title] = reportName;
            folder.Update();
            return folder;
        }

        public ReportRecord AddReportRecord(SPListItem reportFolder)
        {
            return Map(reportFolder.ListItems.Add(reportFolder.Folder.ServerRelativeUrl, SPFileSystemObjectType.File));
        }

        public List<ScanReport> GetAllReports()
        {
            var reportFolders = listResolver.List.GetItems(new SPQuery
            {
                Query = CAML.Where(CAML.Eq(CAML.FieldRef("ContentType"), CAML.Value("Folder"))) //TODO: read these strings from resources
            });

            var result = new List<ScanReport>(reportFolders.Count);
            result.AddRange((from SPListItem folder in reportFolders select new ScanReport(folder)).ToList());
            return result;
        }

        
    }
}